import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    userInfo: null,
    token: null,
    isLogin: false,
    currentLocation: null,
    searchHistory: [],
    consultationList: [],
    orderList: [],
    healthRecords: []
  },
  mutations: {
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_LOGIN_STATUS(state, status) {
      state.isLogin = status
    },
    SET_LOCATION(state, location) {
      state.currentLocation = location
    },
    ADD_SEARCH_HISTORY(state, keyword) {
      if (!state.searchHistory.includes(keyword)) {
        state.searchHistory.unshift(keyword)
        if (state.searchHistory.length > 10) {
          state.searchHistory.pop()
        }
      }
    },
    CLEAR_SEARCH_HISTORY(state) {
      state.searchHistory = []
    },
    SET_CONSULTATION_LIST(state, list) {
      state.consultationList = list
    },
    SET_ORDER_LIST(state, list) {
      state.orderList = list
    },
    SET_HEALTH_RECORDS(state, records) {
      state.healthRecords = records
    }
  },
  actions: {
    login({ commit }, { userInfo, token }) {
      commit('SET_USER_INFO', userInfo)
      commit('SET_TOKEN', token)
      commit('SET_LOGIN_STATUS', true)
      // 存储到本地
      uni.setStorageSync('userInfo', userInfo)
      uni.setStorageSync('token', token)
    },
    logout({ commit }) {
      commit('SET_USER_INFO', null)
      commit('SET_TOKEN', null)
      commit('SET_LOGIN_STATUS', false)
      // 清除本地存储
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    },
    updateLocation({ commit }, location) {
      commit('SET_LOCATION', location)
    },
    addSearchHistory({ commit }, keyword) {
      commit('ADD_SEARCH_HISTORY', keyword)
    },
    clearSearchHistory({ commit }) {
      commit('CLEAR_SEARCH_HISTORY')
    },
    async fetchConsultationList({ commit }) {
      // TODO: 调用API获取问诊列表
      const list = []
      commit('SET_CONSULTATION_LIST', list)
    },
    async fetchOrderList({ commit }) {
      // TODO: 调用API获取订单列表
      const list = []
      commit('SET_ORDER_LIST', list)
    },
    async fetchHealthRecords({ commit }) {
      // TODO: 调用API获取健康档案
      const records = []
      commit('SET_HEALTH_RECORDS', records)
    }
  },
  getters: {
    userInfo: state => state.userInfo,
    isLogin: state => state.isLogin,
    currentLocation: state => state.currentLocation,
    searchHistory: state => state.searchHistory,
    consultationList: state => state.consultationList,
    orderList: state => state.orderList,
    healthRecords: state => state.healthRecords
  }
})

export default store 